/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: liuzicheng
 * @Date: 2025-02-18 10:30:36
 * @LastEditors: liuzicheng
 * @LastEditTime: 2025-02-21 16:26:52
 */
import { ProFormUploadButton, ProFormUploadButtonProps } from "@ant-design/pro-components";
import { Image, message } from "antd";
import Upload, { RcFile } from "antd/es/upload";
import { useState } from "react";
import { LeftOutlined, RightOutlined } from "@ant-design/icons";
import "./index.less";
interface ProFormUploadComProps extends ProFormUploadButtonProps {
  name?: string;
}
const ProFormUploadCom: React.FC<ProFormUploadComProps> = (props) => {
  const { name } = props;
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState<any>("");
  const [fileList, setFileList] = useState<any>();
  const [proviewFile, setProviewFile] = useState<any>(null);

  const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });
  const beforeUpload = (file: RcFile) => {
    const isPNG = ["image/png", "image/jpeg", "image/jpg"].includes(file.type);
    if (!isPNG) {
      message.error(`${file.name} 图片格式不符合`);
      return Upload.LIST_IGNORE;
    }

    const isLt3M = file.size / 1024 / 1024 < 3;
    if (!isLt3M) {
      message.error(`图片大小不能超过3MB`);
      return Upload.LIST_IGNORE;
    }
    return true; // 阻止默认上传行为
  };
  const defaultProps: Pick<ProFormUploadButtonProps, "fieldProps" | "accept" | "extra" | "max" | "title"> = {
    fieldProps: {
      listType: "picture-card",
      onPreview: async (file) => {
        if (!file.preview) {
          file.preview = await getBase64(file.originFileObj as RcFile);
        }
        setPreviewOpen(true);
        setPreviewImage(file.preview);
        setProviewFile(file);
      },
      onChange: (info) => {
        setFileList(info.fileList);
      },
      customRequest: async ({ onSuccess, onError }: any) => {
        try {
          // 将文件读取为base64或者其他格式的文件流
          // const base64 = await getBase64(file as RcFile);
          // console.log('文件流:', base64);

          // 可以根据需求对文件流进行进一步处理，或上传到服务器

          onSuccess("文件处理成功");
        } catch (error) {
          console.log(error);

          onError("文件处理失败");
        }
      },
      beforeUpload
    },
    accept: ".jpg,.png,.jpeg,.gif,.webp",
    extra: "请上传JPEG、PNG或GIF格式的图片，每张大小不超过3MB，最多可上传9张",
    max: 9,
    title: "上传图片"
  };

  return (
    <div className="preview-image">
      <ProFormUploadButton name={name ?? "file"} {...defaultProps} {...props} />
      {previewOpen && (
        <Image
          preview={{
            visible: previewOpen,
            onVisibleChange: (visible) => setPreviewOpen(visible)
          }}
          style={{ display: "none" }}
          src={previewImage}
        />
      )}
      {previewOpen && (
        <div>
          <div
            onClick={async () => {
              const _index = fileList.findIndex((item) => item.uid === proviewFile.uid);
              if (_index > 0) {
                const curImg = fileList[_index - 1];
                setPreviewImage(curImg.preview);
                setProviewFile(curImg);
              } else {
                message.warning("已经是第一张了");
              }
            }}
            className="preview-icon left-icon"
          >
            <LeftOutlined style={{ color: "#fff" }} />
          </div>
          <div
            onClick={async () => {
              const _index = fileList.findIndex((item) => item.uid === proviewFile.uid);
              if (_index < fileList.length - 1) {
                const curImg = fileList[_index + 1];
                setPreviewImage(curImg.preview);
                setProviewFile(curImg);
              } else {
                message.warning("已经是最后一张了");
              }
            }}
            className="preview-icon right-icon"
          >
            <RightOutlined style={{ color: "#fff" }} />
          </div>
        </div>
      )}
    </div>
  );
};

export default ProFormUploadCom;
